// pages/index/bxr/bxrHisData/goodsInfoEdit/goodsInfoEdit.js
const app = getApp()
var http = require('../../../../../service/http.js');
var getTime = require('../../../../../utils/util.js');
var wechat = require('../../../../../utils/wechat.js');
// pages/bdataEntry/bdataEntry.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    select: false,
    tihuoWay: '',
    step: 1,
    // 1

    policy_num: '',
    report_num: '',
    insurance_type: '',
    // 2
    goods_type: '',
    goods_name: '',
    goods_num: '',
    good_price: '',
    good_pg_price: '',
    // 3
    damage_at: '',
    damage_result: '',
    address: '',
    address_detail: '',
    other_report: '',
    // 4
    present_at: '',
    goods_list: [],
    goods_desc: '',
    present_img: [],
    present_video: [],
    // 5
    should_at: '',
    rem_company: '',
    linkman: '',
    connect_phone: '',
    // 6
    author_report: [],

    newTime: '',
    insuranceTypeList: [],
    goodsTypeList: [],
    goodsTypeIndex: '',
    insuranceTypeIndex: 0,
    damageResultNum: 0,
    damageResultMaxNum: 200,
    goodsDescNum: 0,
    goodsDescMaxNum: 200,
    // 照片
    evalList: [{ tempFilePaths: [], imgList: [] }],
    landed: false,
    showModal: false,
    showWebView: false
  },
  one_policy_num(e) {
    this.setData({
      policy_num: e.detail.value
    })
  },
  one_report_num(e) {
    this.setData({
      report_num: e.detail.value
    })
  },
  two_goods_name(e) {
    this.setData({
      goods_name: e.detail.value
    })
  },
  two_goods_num(e) {
    this.setData({
      goods_num: e.detail.value
    })
  },
  two_good_price(e) {
    this.setData({
      good_price: e.detail.value
    })
  },
  two_good_pg_price(e) {
    this.setData({
      good_pg_price: e.detail.value
    })
  },
  //受损原因
  three_damage_result(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      damageResultNum: e.detail.value.length,
      damage_result: e.detail.value
    })
  },
  three_address_detail(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      address_detail: e.detail.value
    })
  },
  four_goods_desc(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      goodsDescNum: e.detail.value.length,
      goods_desc: e.detail.value
    })
  },
  five_rem_company(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      rem_company: e.detail.value
    })
  },
  five_linkman(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      linkman: e.detail.value
    })
  },
  five_connect_phone(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      connect_phone: e.detail.value
    })
  },
  lookTemplate() {
    wx.navigateTo({
      url: '../template/template',
    })
  },
  //选择时间
  bindShouldChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      should_at: e.detail.value
    })
  },
  bindPresentChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      present_at: e.detail.value
    })
  },
  bindDamageChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      damage_at: e.detail.value
    })
  },
  //选择省市区
  bindAddressChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      address: e.detail.value
    })
  },
  preview:function(e){
    var url = e.currentTarget.dataset.src
    console.log(url)
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  //货物类别
  getGoodsType(goodtype) {
    var _this = this;
    http.getReq('/index/index/goodsType',{}, res => {
      if (goodtype) {
        res.data.type_list.forEach((i,key)=> {
          if (i.gt_id == goodtype) {
            this.setData({
              goods_type: i.gt_id,
              goodsTypeIndex: key
            })
          }
        });
      }
      _this.setData({goodsTypeList: res.data.type_list})
    })
     
  },
  //保险种类
  getInsuranceType(chosedid) {
    chosedid = chosedid ? chosedid :'';
    var chose_arr=chosedid.split(",");
    http.getReq('/index/index/getInsuranceType',{}, res => {
      var insuranceTypeSelected = [];
      var insuranceTypeSelectedID = [];
      res.data.type_list.forEach(i =>{
        i.checked = false
        if(chose_arr.indexOf(i.it_id) >-1){
            i.checked = true;
            insuranceTypeSelected.push(i.it_name);
            insuranceTypeSelectedID.push(i.it_id);
        }
      });
      this.setData({
        insuranceTypeSelected: insuranceTypeSelected.join(','),
        insuranceTypeSelectedID: insuranceTypeSelectedID.join(','),
        insuranceTypeList: res.data.type_list,
      })
    })
  },
  goodsTypeList(e) {
    let typeList = this.data.goodsTypeList;
    this.setData({
      goodsTypeIndex: e.detail.value,
      goods_type: typeList[e.detail.value].gt_id
    })
  },
  insuranceTypeList(e) {
    let typeList = this.data.insuranceTypeList;
    this.setData({
      insuranceTypeIndex: e.detail.value,
      insurance_type: typeList[e.detail.value].it_id
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onReady() {
    this.setData({
      newTime: getTime(new Date())
    })
  },
  onLoad: function (options) {
    this.setData({
      step: options.step,
    });
    let _data = JSON.parse(options.info);
    console.log(_data)
    let _this = this;
    this.getInsuranceType(_data.goods_info.insurance_type) //出险险种
    this.getGoodsType(_data.goods_info.goods_type) //货物类别
    let address = []
    address.push(_data.goods_info.omit)
    address.push(_data.goods_info.city)
    address.push(_data.goods_info.classify)
    console.log(address)
    this.setData({
      policy_num: _data.goods_info.policy_num ? _data.goods_info.policy_num : '',
      report_num: _data.goods_info.report_num ? _data.goods_info.report_num : '',
      insurance_type: _data.goods_info.insurance_type ? _data.goods_info.insurance_type : '',
      // 2
      goods_type: _data.goods_info.goods_type ? _data.goods_info.goods_type : '',
      goods_name: _data.goods_info.goods_name ? _data.goods_info.goods_name : '',
      goods_num: _data.goods_info.goods_num ? _data.goods_info.goods_num : '',
      good_price: _data.goods_info.good_price ? _data.goods_info.good_price : '',
      good_pg_price: _data.goods_info.good_pg_price ? _data.goods_info.good_pg_price : '',
      // 3
      damage_at: _data.goods_info.damage_at ? _data.goods_info.damage_at : '',
      damage_result: _data.goods_info.damage_result ? _data.goods_info.damage_result : '',
      address: address.length > 0 ? address:'请选择地区',
      address_detail: _data.goods_info.address_detail ? _data.goods_info.address_detail : '',
      /*  一片天空*/
      other_report: _data.goods_info.other_report ? _data.goods_info.other_report : [],
      // 4
      present_at: _data.goods_info.present_at ? _data.goods_info.present_at : '',
      goods_list: _data.goods_info.goods_list ? _data.goods_info.goods_list : [],
      goods_desc: _data.goods_info.goods_desc ? _data.goods_info.goods_desc : '',
      /*  一片天空 start  添加类型判断*/
      present_img: _data.goods_info.present_img ? typeof(_data.goods_info.present_img) == 'string' ? _data.goods_info.present_img.split(',') : _data.goods_info.present_img : [],
      present_video: _data.goods_info.present_video ?typeof(_data.goods_info.present_video) == 'string' ? _data.goods_info.present_video.split(',') : _data.goods_info.present_video : [],
      /*  一片天空 end*/

      // 5
      should_at: _data.goods_info.should_at ? _data.goods_info.should_at : '',
      rem_company: _data.goods_info.rem_company ? _data.goods_info.rem_company : '',
      linkman: _data.goods_info.linkman ? _data.goods_info.linkman : '',
      connect_phone: _data.goods_info.connect_phone ? _data.goods_info.connect_phone : '',
      // 6
      author_report: _data.goods_info.author_report ? _data.goods_info.author_report.split(',') : [],
    })
  },
  bindShowMsg() {
    this.setData({
      select: !this.data.select
    })
  },
  mySelect(e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      tihuoWay: name,
      select: false
    });
  },
  nextStep(e) {
    let pages = getCurrentPages();//当前页面
    let prevPage = pages[pages.length - 2];//上一页面\

    let policy_num = 'goodsInfo.goods_info.policy_num'
    let report_num = 'goodsInfo.goods_info.report_num'
    let insurance_type = 'goodsInfo.goods_info.insurance_type'
    let insurance_type_name = 'goodsInfo.goods_info.insurance_type_name'

    let goods_type = 'goodsInfo.goods_info.goods_type'
    let goods_type_name = 'goodsInfo.goods_info.goods_type_name'
    let goods_name = 'goodsInfo.goods_info.goods_name'
    let goods_num = 'goodsInfo.goods_info.goods_num'
    let good_price = 'goodsInfo.goods_info.good_price'
    let good_pg_price = 'goodsInfo.goods_info.good_pg_price'


    let damage_at = 'goodsInfo.goods_info.damage_at'
    let damage_result = 'goodsInfo.goods_info.damage_result'
    let address = 'goodsInfo.goods_info.address'
    let address_detail = 'goodsInfo.goods_info.address_detail'
    let other_report = 'goodsInfo.goods_info.other_report'

    let present_at = 'goodsInfo.goods_info.present_at'
    let goods_list = 'goodsInfo.goods_info.goods_list'
    let goods_desc = 'goodsInfo.goods_info.goods_desc'
    let present_img = 'goodsInfo.goods_info.present_img'
    let present_video = 'goodsInfo.goods_info.present_video'

    let should_at = 'goodsInfo.goods_info.should_at'
    let rem_company = 'goodsInfo.goods_info.rem_company'
    let linkman = 'goodsInfo.goods_info.linkman'
    let connect_phone = 'goodsInfo.goods_info.connect_phone'

    let author_report = 'goodsInfo.goods_info.author_report'
    console.log(this.data.step)
    console.log(this.data.goods_list)
    if (this.data.step == '1') {
      prevPage.setData({
        [policy_num]: this.data.policy_num,
        [report_num]: this.data.report_num,
        [insurance_type]: this.data.insurance_type,
        [insurance_type_name]: this.data.insuranceTypeList[this.data.insuranceTypeIndex].it_name,
      })
    } else if (this.data.step == '2') {
      let gt_name = ''
      let idx = this.data.goodsTypeIndex
      gt_name = this.data.goodsTypeList[idx].gt_name
      prevPage.setData({
        [goods_type]: this.data.goods_type,
        [goods_type_name]: gt_name,
        [goods_name]: this.data.goods_name,
        [goods_num]: this.data.goods_num,
        [good_price]: this.data.good_price,
        [good_pg_price]: this.data.good_pg_price,
      })
    } else if (this.data.step == '3') {
      console.log(this.data.address)
      prevPage.setData({
        [damage_at]: this.data.damage_at,
        [damage_result]: this.data.damage_result,
        address: this.data.address ? this.data.address.join(',') : '',
        [address_detail]: this.data.address_detail,
        [other_report]: this.data.other_report ? this.data.other_report : '',
      })
    } else if (this.data.step == '4') {
      console.log(this.data.goods_list)
      prevPage.setData({
        [present_at]: this.data.present_at,
        [goods_list]: this.data.goods_list,
        [goods_desc]: this.data.goods_desc,
        [present_img]: this.data.present_img && this.data.present_img.length ? this.data.present_img : '',
        [present_video]: this.data.present_video && this.data.present_video.length ? this.data.present_video : '',
      })
    } else if (this.data.step == '5') {
      prevPage.setData({
        [should_at]: this.data.should_at,
        [rem_company]: this.data.rem_company,
        [linkman]: this.data.linkman,
        [connect_phone]: this.data.connect_phone,
      })
    } else if (this.data.step == '6') {
      prevPage.setData({
        [author_report]: this.data.author_report && this.data.author_report.length ? this.data.author_report[0] : '',
      })
    }
    wx.navigateBack();
  },
  preStep(e) {
    const _this = this;
    wx.showModal({
      title: '提示',
      content: '取消后是否要保存本次编辑',
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
          _this.setData({
            step: JSON.parse(e.target.dataset.index) - 1
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.landed) {
      this.setData({landed: true});
      return;
    }
    if(!this.data.showWebView) {
      this.setData({showWebView: false});
      return;
    }
    http.getReq('/index/user/getRole',{},_res=>{
      http.postReq('/index/upload/get_upload_url', {
        phone: _res.data.phone
      }, res => {
        if (res.data.url) {
        var inList = false;
        var url = res.data.url;
        console.log(this.data.goods_list)
        this.data.goods_list.forEach(i => {
          if (i === url) {
          inList = true;
        }
      });
        if (!inList) {
          var name = res.data.url_name;
          var list = this.data.goods_list;
          list.push({url: url, name: name});
          this.setData({goods_list: list});
        console.log(this.data.goods_list)

        }
      }
    });
  })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // joinPicture: function (e) {
  //   var index = e.currentTarget.dataset.index;
  //   var evalList = this.data.evalList;
  //   var that = this;
  //   var imgNumber = evalList[index].tempFilePaths;
  //   if (imgNumber.length >= 3) {
  //     wx.showModal({
  //       title: '',
  //       content: '最多上传三张图片',
  //       showCancel: false,
  //     })
  //     return;
  //   }
  //   wx.showActionSheet({
  //     itemList: ["从相册中选择", "拍照"],
  //     itemColor: "#f7982a",
  //     success: function (res) {
  //       if (!res.cancel) {
  //         if (res.tapIndex == 0) {
  //           that.chooseWxImage("album", imgNumber);
  //         } else if (res.tapIndex == 1) {
  //           that.chooseWxImage("camera", imgNumber);
  //         }
  //       }
  //     }
  //   })
  // }, //选择视频

  // chooseVideo: function () {

  //   var that = this

  //   wx.chooseVideo({

  //     success: function (res) {

  //       that.setData({

  //         src: res.tempFilePath,

  //       })

  //     }

  //   })

  // },
  delGoodsFile(e) {
    var goods_list = this.data.goods_list;
    var arr = [];
    for (var i = 0; i < goods_list.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(goods_list[i])
      }
    }
    // imgList =
    this.setData({
      goods_list: arr
    })
  },
  delSanfile(e) {
    console.log(e)
    var other_report = this.data.other_report;
    var arr = [];
    for (var i = 0; i < other_report.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(other_report[i])
      }
    }
    // imgList =
    this.setData({
      other_report: arr
    })
  },
  delImg(e) {
    console.log(e)
    var present_img = this.data.present_img;
    var arr = [];
    for (var i = 0; i < present_img.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(present_img[i])
      }
    }
    // imgList =
    this.setData({
      present_img: arr
    })
  },
  delVideo(e) {
    console.log(e)
    var present_video = this.data.present_video;
    var arr = [];
    for (var i = 0; i < present_video.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(present_video[i])
      }
    }
    this.setData({
      present_video: arr
    })
  },

  delAuthorReportFile(e) {
    var author_report = this.data.author_report;
    var arr = [];
    for (var i = 0; i < author_report.length; i++) {
      console.log(e.currentTarget.dataset.index)
      if (i == e.currentTarget.dataset.index) {
      } else {
        arr.push(author_report[i])
      }
    }
    // imgList =
    this.setData({
      author_report: arr
    })
  },
  authorReportFile() {
    wechat.chooseImage()
      .then(d => {
        let { path, size } = d.tempFiles[0];
        // let params = this.data.present_img;
        // params.push(path)
        // this.setData({
        //   tempImagePath: path,
        // });
        // console.log(path)
        return wechat.uploadFile("/index/Upload/index", path, "avatar")
      })
      .then(d => {
        let res = JSON.parse(d.data)
        let author_report = this.data.author_report
        author_report[0] = res.data.url
        // author_report.push(res.data.url)
        // console.log(author_report)
        this.setData({
          author_report: author_report
        })
      })
      .catch(e => {
        console.log(e);
      })
  },
  // 第三方报告
  sanfile() {
    wechat.chooseImage()
      .then(d => {
        wx.showLoading({title: '上传中', mask: true});
        let { path, size } = d.tempFiles[0];
        // let params = this.data.present_img;
        // params.push(path)
        // this.setData({
        //   tempImagePath: path,
        // });
        // console.log(path)
        return wechat.uploadFile("/index/Upload/index", path, "avatar")
      })
      .then(d => {
        wx.hideLoading();
        let res = JSON.parse(d.data)
        let other_report = this.data.other_report
        other_report.push(res.data.url)
        console.log(other_report)
        this.setData({
          other_report: other_report
        })
      })
      .catch(e => {
        wx.hideLoading();
        console.log(e);
      })
  },
  // 货品清单
  goodsFile() {
    this.setData({showWebView: true});
    http.getReq('/index/user/getRole',{}, res=>{
      wx.navigateTo({
        url: '/pages/public/webView/webView?phone='+res.data.phone
      });
    })
    // wechat.chooseImage()
    //   .then(d => {
    //     let { path, size } = d.tempFiles[0];
    //     // let params = this.data.present_img;
    //     // params.push(path)
    //     // this.setData({
    //     //   tempImagePath: path,
    //     // });
    //     // console.log(path)
    //     return wechat.uploadFile("/index/Upload/index", path, "avatar")
    //   })
    //   .then(d => {
    //     let res = JSON.parse(d.data)
    //     let goods_list = this.data.goods_list
    //     goods_list.push(res.data.url)
    //     console.log(goods_list)
    //     this.setData({
    //       goods_list: goods_list
    //     })
    //   })
    //   .catch(e => {
    //     console.log(e);
    //   })
  },


  // 货物清单
  camera(e) {
    let { type } = e.target.dataset;
    this.setData({
      type
    })
    console.log("开始上传准备", type == "chooseImage" ? "图片" : "视频");
    // 拍照
    if (type == "chooseImage") {
      console.log("选择图片");
      wechat.chooseImage()
        .then(d => {
          wx.showLoading({title: '上传中', mask: true});
          let { path, size } = d.tempFiles[0];
          // let params = this.data.present_img;
          // params.push(path)
          // this.setData({
          //   tempImagePath: path,
          // });
          return wechat.uploadFile("/index/Upload/index", path, "avatar")
        })
        .then(d => {
          wx.hideLoading();
          let res = JSON.parse(d.data)
          let present_img = this.data.present_img
          present_img.push(res.data.url)
          console.log(present_img)
          this.setData({
            present_img: present_img
          })
        })
        .catch(e => {
          console.log(e);
        })
    }
    // 录视频
    else if (type == "chooseVideo") {
      wechat.chooseVideo()
        .then(d => {
          console.log(d);
      wx.showLoading({title: '上传中', mask: true});
          let { tempFilePath, thumbTempFilePath, size } = d;
          // let params = this.data.present_video
          // params.push(present_video)
          // this.setData({
          //   // tempThumbPath: thumbTempFilePath,
          //   tempVideoPath: params,
          // });
          return wechat.uploadFile("/index/Upload/index", tempFilePath, "avatar");
        })
        .then(d => {
        wx.hideLoading();
          let res = JSON.parse(d.data)
          let present_video = this.data.present_video
          present_video.push(res.data.url)
          this.setData({
            present_video: present_video
          })
        })
        .catch(e => {
        wx.hideLoading();
          console.log(e);
        })
    }
  },
  onShareAppMessage: function () {
    return {
      title: '融易拍',
      path: '/pages/login/login/login'
    }
  },
  // chooseWxImage: function (type, list) {
  //   var img = list;
  //   var len = img.length;
  //   var that = this;
  //   var evalList = this.data.evalList;
  //   wx.chooseImage({
  //     count: 3,
  //     sizeType: ["original", "compressed"],
  //     sourceType: [type],
  //     success: function (res) {
  //       var addImg = res.tempFilePaths;
  //       var addLen = addImg.length;
  //       if ((len + addLen) > 3) {
  //         for (var i = 0; i < (addLen - len); i++) {
  //           var str = {};
  //           str.pic = addImg[i];
  //           img.push(str);
  //         }
  //       } else {
  //         for (var j = 0; j < addLen; j++) {
  //           var str = {};
  //           str.pic = addImg[j];
  //           img.push(str);
  //         }
  //       }
  //       that.setData({
  //         evalList: evalList
  //       })
  //       that.upLoadImg(img);
  //     },
  //   })
  // },
  // upLoadImg: function (list) {
  //   var that = this;
  //   this.upload(that, list);
  // },
  // //多张图片上传
  // upload: function (page, path) {
  //   var that = this;
  //   var curImgList = [];
  //   for (var i = 0; i < path.length; i++) {
  //       wx.uploadFile({
  //         url: app.globalData.subDomain + '/API/AppletApi.aspx',//接口处理在下面有写
  //         filePath: path[i].pic,
  //         name: 'file',
  //         header: { "Content-Type": "multipart/form-data" },
  //         formData: {
  //           douploadpic: '1'
  //         },
  //         success: function (res) {
  //           curImgList.push(res.data);
  //           var evalList = that.data.evalList;
  //           evalList[0].imgList = curImgList;
  //           that.setData({
  //             evalList: evalList
  //           })
  //           if (res.statusCode != 200) {
  //             wx.showModal({
  //               title: '提示',
  //               content: '上传失败',
  //               showCancel: false
  //             })
  //             return;
  //           }
  //           var data = res.data
  //           page.setData({  //上传成功修改显示头像
  //             src: path[0]
  //           })
  //         },
  //         fail: function (e) {
  //           wx.showModal({
  //             title: '提示',
  //             content: '上传失败',
  //             showCancel: false
  //           })
  //         },
  //         complete: function () {
  //           wx.hideToast();  //隐藏Toast
  //         }
  //       })
  //   }
  // },
})
